package com.wangx1n.tset;

import com.wangx1n.bean.Emp;
import com.wangx1n.service.UserService;
import com.wangx1n.spring5.Book;
import com.wangx1n.spring5.Order;
import com.wangx1n.spring5.User;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author WangXin
 * @date 2020/12/2 15:45
 */
public class MyTest {
    /**
     * spring hello
     */
    @Test
    public void testAdd() {
        //加载spring配置文件
        BeanFactory context = new ClassPathXmlApplicationContext("bean1.xml");
        //获取user对象
        User user = context.getBean("user", User.class);
        //检查user对象是否存在
        System.out.println(user);
        //调用user方法
        user.add();
    }

    /**
     * 反射测试
     */
    @Test
    public void fanshe() {
        try {
//        获取字节码
            Class clazz = Class.forName("com.wangx1n.spring5.User");
//       新建对象并且强转
            User user = (User) clazz.newInstance();
//        测试对象是否创建成功
            user.add();
        } catch (Exception e) {
            System.out.println("反射测试错误");
        }
    }


//-----------------------------------------

    /**
     * 通过set属性注入
     */
    @Test
    public void testBook() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        Book book = context.getBean("book", Book.class);
        book.print();
    }

    /**
     * 通过构造器注入
     */
    @Test
    public void testOrder() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        Order order = context.getBean("order", Order.class);
        order.print();
    }

    /**
     * 特殊注入-外部bean
     */
    @Test
    public void inbean1() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
    }

    /**
     * 内部注入
     */
    @Test
    public void inbean2() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean3.xml");
        Emp emp = context.getBean("emp", Emp.class);
        emp.print();

    }


    /**
     * 级联注入
     */
    @Test
    public void inbean3() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml");
        Emp emp = context.getBean("emp", Emp.class);
        emp.print();

    }





    /**
     * 简单ioc
     *
     * @return
     * @throws Exception
     */
    public static Object MyIoc() throws Exception {
        //xml解析获得
        String classPath = "com.wangx1n.spring5.User";
        //新建反射对象
        Class clazz = Class.forName(classPath);
        //创建对象并返回
        return clazz.newInstance();
    }
}
